from django.http import Http404, HttpResponseRedirect
from .models import Question, Choice
from django.urls import reverse
from django.utils import timezone


def index(request):

    latest_question_list = Question.objects.filter(pub_date__lte=timezone.now()).order_by('-pub_date')[:5]

    context = {'latest_question_list': latest_question_list}

    return render(request, 'polls/index_1.html', context)


def detail(request, id):
    try:
        latest_question_list = Question.objects.get(id=id)
    except Question.DoesNotExist:
        raise Http404("请重试")

    context = {'question': latest_question_list}

    return render(request, 'polls/index_3.html', context)


def vote(request, question_id):
    question = get_object_or_404(Question, pk=question_id)

    try:

       list_1 = question.choice_set.get(pk=request.POST['choice'])

    except (KeyError, Choice.DoesNotExist):

        return render(request, 'polls/index_3.html', {'question': question, 'error_message': "请重试", })

    else:

       list_1.votes += 1

       list_1.save()

       return HttpResponseRedirect(reverse('polls:results', args=(question.id,)))




from django.shortcuts import get_object_or_404, render


def results(request, question_id):
    question = get_object_or_404(Question, id=question_id)
    return render(request, 'polls/results.html', {'question': question})
















